package com.recycle.intercept;

import com.google.gson.Gson;

import com.recycle.common.base.BaseInfoProperties;
import com.recycle.common.exceptions.GraceException;
import com.recycle.common.result.ResponseStatusEnum;
import com.recycle.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JWTCurrentUserInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    public static ThreadLocal<SysUser> currentUser = new ThreadLocal<>();

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 使用ThreadLocal可以在同一个线程内共享数据
        // 比如：Interceptor --> 控制器Controller --> 业务层Service --> 数据层Mapper(dao)

        String userJson = request.getHeader(TOKEN);
        log.info("-----------------url:{}",request.getRequestURI());
        if(request.getRequestURL().toString().contains("error")){
            return true;
        }

        if (StringUtils.isNotBlank(userJson)) {
            SysUser user = new Gson().fromJson(userJson, SysUser.class);
            if(user == null){
                GraceException.display(ResponseStatusEnum.UN_LOGIN);
            }
            currentUser.set(user);
        }else{
            GraceException.display(ResponseStatusEnum.UN_LOGIN);
        }
        /**
         * false: 请求被拦截
         * true: 放行，请求验证通过
         */
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        currentUser.remove();
    }
}
